package com.mego.tzadd.activitys;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessaging;
import com.mego.tzadd.R;
import com.mego.tzadd.database.dbmodel.SystemAllInfo;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.utils.Config;
import com.mego.tzadd.utils.HttpRequest;
import com.mego.tzadd.utils.NotificationUtils;
import com.mego.tzadd.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.util.JSON;

//问题反馈
public class LoginActivity extends BaseActivity implements View.OnClickListener, AlertDialog.OnDialogButtonClickListener {

    private final String TAG = "LoginActivity";

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    public static Intent createIntent(Context context) {
        return new Intent(context, LoginActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    private BroadcastReceiver mRegistrationBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        initView();
        initData();
        initEvent();




        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);
                    displayFirebaseRegId();
                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received
                    String message = intent.getStringExtra("message");
                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
//                    txtMessage.setText(message);
                }
            }
        };


        //检索当前注册令牌
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        _fcmtoken = task.getResult().getToken();
                        Utils.log("FirebaseInstanceId--- token= " + _fcmtoken + "\n");
                    }
                });
    }

    String _fcmtoken = "";

    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

//        if (!TextUtils.isEmpty(regId))
//            txtRegId.setText("Firebase Reg Id: " + regId);
//        else
//            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    public void onForwardClick(View v) {

    }

    private EditText edit_username;
    private EditText edit_mima;
    private ImageView iv_jzusermima;

    @Override
    public void initView() {
        edit_username = (EditText) findViewById(R.id.edit_username);
        edit_mima = (EditText) findViewById(R.id.edit_mima);
        iv_jzusermima = (ImageView) findViewById(R.id.iv_jzusermima);
    }

    @Override
    public void initData() {

        SystemAllInfo jzusermima = SystemCenter.getInstance().getSysInfo("jzusermima");
        if (jzusermima != null) {
            if (Integer.parseInt(jzusermima.getContent()) == 0) {
                _jzusermima = false;
            }
        }

        if (_jzusermima) {
            iv_jzusermima.setBackgroundResource(R.mipmap.btn_checkbox_pressed);
        } else {
            iv_jzusermima.setBackgroundResource(R.mipmap.btn_checkbox_normal);
        }

        SystemAllInfo lastusername = SystemCenter.getInstance().getSysInfo("lastusername");
        if (lastusername != null) {
            _username = lastusername.getContent();
            edit_username.setText(_username);

            SystemAllInfo mima = SystemCenter.getInstance().getSysInfo(lastusername.getContent());
            if (mima != null && _jzusermima) {
                _mima = mima.getContent();
                edit_mima.setText(_mima);
//                onLogin();
            }
        }
    }

    private void onRegitst() {
        Intent intent = new Intent(LoginActivity.this, RegistActivity.class);
        startActivityForResult(intent, REQUEST_TO_REGITST);
    }

    String _username = "";
    String _mima = "";
    boolean _jzusermima = true;

    @Override
    public void initEvent() {
        findViewById(R.id.tv_login).setOnClickListener(this);
        findViewById(R.id.iv_jzusermima).setOnClickListener(this);
        findViewById(R.id.tv_regitst).setOnClickListener(this);
        findViewById(R.id.iv_wjmm).setOnClickListener(this);

        showTx();
    }

    void showTx() {
        new AlertDialog(this, "注意事項", "1. 啟用強制消保時，請自行確認機台營運狀況，以免發生爭議!\n" +
                "2. 機台保夾金額請確實設置，不正確的設定會導致自動消保功能異常!\n3. APP會使用即時的定位位置，排列裝置的順序，不會將定位紀錄用做其他用途!", false, "確認", 13, this).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_login:
                onLogin();
                break;
            case R.id.iv_jzusermima:
                onJzmima();
                break;
            case R.id.tv_regitst:
                onRegitst();
                break;
            case R.id.iv_wjmm:
                onWjmm();
                break;
        }
    }

    private void onWjmm() {
        _username = edit_username.getText().toString();
        SystemCenter.getInstance().username = _username;
        Intent intent = new Intent(LoginActivity.this, WjmmActivity.class);
        startActivityForResult(intent, REQUEST_TO_WJMM);
    }

    private void onJzmima() {
        _jzusermima = !_jzusermima;
        if (_jzusermima) {
            iv_jzusermima.setBackgroundResource(R.mipmap.btn_checkbox_pressed);
        } else {
            iv_jzusermima.setBackgroundResource(R.mipmap.btn_checkbox_normal);
        }
    }

    boolean _islogining = false;

    private void onLogin() {
        _username = edit_username.getText().toString();
        _mima = edit_mima.getText().toString();
        if (_username.isEmpty() || _mima.isEmpty()) {
            showShortToast("请输入用户名和密碼！");
            return;
        }

        if (_islogining) {
            return;
        }

//        SharedPreferences sp = context.getSharedPreferences(
//                "tzaddfcm", Context.MODE_PRIVATE);
//
//        String token = sp.getString("fcmtoken", "");

        Utils.log("login token=" + _fcmtoken);

        showProgressDialog(R.string.loading);

        _islogining = true;

        try {
            HttpRequest.login(_username, _mima, _fcmtoken, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    _islogining = false;
                    dismissProgressDialog();
                    if (code == 1) {
                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        SystemCenter.getInstance().adminid = data.getLong("adminid");
                        SystemCenter.getInstance().username = _username;
                        String email = data.getString("email");
                        SystemCenter.getInstance().email = email;
                        SystemCenter.getInstance().mobile = data.getString("mobile");

                        finishlogin();
                    } else {
                        showShortToast("登錄失败");
                    }
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            _islogining = false;
            dismissProgressDialog();
        }
    }

    private void finishlogin() {
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "lastusername", _username));
        if (_jzusermima) {
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "jzusermima", "1"));
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, _username, _mima));
        } else {
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "jzusermima", "0"));
        }

        Intent intent = new Intent(LoginActivity.this, MainTabActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 13) {
//            doDdlj();
        }
    }

    private final int REQUEST_TO_WJMM = 13;
    private final int REQUEST_TO_REGITST = 16;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_TO_WJMM:
                break;
            case REQUEST_TO_REGITST:
                break;
        }
    }


}

